//
//  UserVC.m
//  NewNest
//
//  Created by 王阳阳 on 16/3/8.
//  Copyright © 2016年 www.lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "UserVC.h"
#import "UserCell.h"//collectionView的自定义cell
#import "UserViewController.h"
#import "AboutUsVC.h"
#import "ClearData.h"
#import "QRCodeReaderViewController.h"
#import "QRCodeReader.h"
#import "ScanVC.h"
#import "NewNestHeader.h"
#import <MessageUI/MessageUI.h>//发邮件
#import <RongIMKit/RongIMKit.h>
#import "SkinViewController.h"
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#import <TencentOpenAPI/TencentOAuth.h>
@interface UserVC ()<UICollectionViewDataSource, UICollectionViewDelegate,UIAlertViewDelegate,QRCodeReaderDelegate,MFMailComposeViewControllerDelegate,TencentSessionDelegate, TencentLoginDelegate>
@property(nonatomic,strong)CLGeocoder *geocoder;
@property (nonatomic, strong) UIButton *nightModalButton;/**< 夜间模式按钮 */
@property (nonatomic, strong) UIImageView *backImg;//背景图片
@property (nonatomic, strong) UIImageView *userImg;//头像
@property (nonatomic, strong) UICollectionView *collectionView;//collectionView
@property (nonatomic, strong) UILabel *nameLabel;//名字
@property (nonatomic, strong) UserCell *cell;//collectionView的cell
@property (nonatomic, strong) NSMutableArray *nameArr;//collectionView标题数组
@property (nonatomic, strong) NSMutableArray *picArr;//collectionView图片数组
@property (nonatomic, retain) UIAlertView *alertview; /**< 扫码弹出框 */
@property (nonatomic, retain) NSString *webUrl; /**< 扫码得到的网址 */
@property (nonatomic, retain) NSString *strstr;
@property (nonatomic, strong)TencentOAuth *tencentOAuth;/**< qq */
@end

@implementation UserVC



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor clearColor];//背景颜色
    self.navigationItem.title = @"我的";
    //导航栏按钮视图
    [self creatNavi];
    //collectionView 头部视图
    [self creatView];
    //创建CollecTionView
    [self creatCollectionView];
    
    
}
#pragma mark - 导航栏按钮
- (void)creatNavi
{
    // 左侧切换模式的按钮
    self.nightModalButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.nightModalButton.frame = CGRectMake(0, 0, 25, 25);
    [self.nightModalButton setImage:[UIImage imageNamed:@"moon"] forState:UIControlStateNormal];
    [self.nightModalButton setImage:[UIImage imageNamed:@"sun"] forState:UIControlStateSelected];
    [self.nightModalButton addTarget:self action:@selector(nightModel) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_nightModalButton];
 
    //右侧登陆按钮
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"登录" style:UIBarButtonItemStylePlain target:self action:@selector(denglu)];

}
#pragma mark - 夜间模式点击按钮
- (void)nightModel
{
    NSLog(@"夜间模式");
    _nightModalButton.selected = !_nightModalButton.selected;
    if (![AccountManager sharedInstance].isNight) {
        self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
        self.tabBarController.tabBar.barStyle = UIBarStyleBlack;
        self.view.backgroundColor = [UIColor grayColor];
        self.collectionView.backgroundColor = [UIColor grayColor];
        
    } else {
        self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
        self.tabBarController.tabBar.barStyle = UIBarStyleDefault;
        self.view.backgroundColor = [UIColor whiteColor];
        self.collectionView.backgroundColor = [UIColor clearColor];

    }
    [AccountManager sharedInstance].isNight = ![AccountManager sharedInstance].isNight;
}


#pragma mark - 创建collectionView
- (void)creatCollectionView
{
    //Layout布局
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.itemSize = CGSizeMake((self.view.frame.size.width - 25) / 4, (self.view.frame.size.width - 25) / 3.5);
    layout.sectionInset = UIEdgeInsetsMake(5, 10, 5, 10);
    //创建CollectionView
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height / 3.2 + 64, self.view.frame.size.width, self.view.frame.size.height - self.view.frame.size.height / 3.5 + 64) collectionViewLayout:layout];
    
    _collectionView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_collectionView];
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    // 注册重用池
    [_collectionView registerClass:[UserCell class] forCellWithReuseIdentifier:@"cell"];
    
    NSArray *arr =@[@"我的精选",@"我的攻略",@"导航定位",@"意见反馈",@"关于我们",@"清除缓存",@"一键换肤",@"即时通讯",@"扫一扫"];
    self.nameArr = [arr mutableCopy];
    NSArray *picARR = @[@"C13",@"C14",@"C15",@"C16",@"C17",@"C18",@"C19",@"C22",@"C21"];
    self.picArr = [picARR mutableCopy];
    
}
#pragma mark - CollecTionView必须实现的两个方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 9;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    self.cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    _cell.backgroundColor = [UIColor clearColor];
            _cell.nameLabel.text = _nameArr[indexPath.row];
    
            _cell.imageview.image = [UIImage imageNamed:_picArr[indexPath.row]];
    return _cell;
}
#pragma mark - collectionView上面的View
- (void)creatView{
    //背景图片
    self.backImg = [[UIImageView alloc]initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height / 3.2)];
    _backImg.image = [UIImage imageNamed:@"backImg9.jpg"];
    [self.view addSubview:_backImg];
    
    
    //加模糊效果
    UIBlurEffect *b = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    UIVisualEffectView *effect = [[UIVisualEffectView alloc] initWithEffect:b];
    effect.frame = CGRectMake(0, 0, self.backImg.frame.size.width, self.backImg.frame.size.height);
    effect.alpha = 0.5;
    [self.backImg addSubview:effect];
    
    
   //底部灰色View
    UIView *bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, self.backImg.frame.size.height  - (self.backImg.frame.size.height / 4), self.backImg.frame.size.width, self.backImg.frame.size.height / 4)];
    //半透明
    bottomView.alpha = 0.5;
    //view颜色
    bottomView.backgroundColor = [UIColor grayColor];
    [self.backImg addSubview:bottomView];
    //灰色条上的button
    UIButton *but = [UIButton buttonWithType:UIButtonTypeSystem];
    but.frame = CGRectMake(0, bottomView.frame.origin.y + 10, self.backImg.frame.size.width, 30);
    //button名字
    [but setTitle:[[NSUserDefaults standardUserDefaults] objectForKey:@"name"] forState:UIControlStateNormal];
    
    [but addTarget:self action:@selector(denglu) forControlEvents:UIControlEventTouchUpInside];
    //button字体颜色
    [but setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    
    [self.backImg addSubview:but];
    
    
 
    
    //用户头像
    self.userImg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.height / 10.5, self.view.frame.size.height / 10.5)];
    _userImg.center = CGPointMake(self.backImg.center.x, self.backImg.frame.size.height / 2);
    //头像
    
    [_userImg sd_setImageWithURL:[[NSUserDefaults standardUserDefaults] objectForKey:@"image"]];
    //圆角
    _userImg.layer.cornerRadius = _userImg.frame.size.width / 2;
    _userImg.clipsToBounds = YES;
    // 开启用户交互
    _userImg.userInteractionEnabled = YES;
    [self.backImg addSubview:_userImg];
    
}
#pragma mark - CollectionView点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    //三个页面的收藏
    if (indexPath.item == 0 || indexPath.item == 1) {
        UserViewController *user = [[UserViewController alloc]init];
        user.str = _nameArr[indexPath.item];
        NSArray *arr = @[@"Boutique",@"Strategy"];
        user.judgeStr = arr[indexPath.item];
        
        [self.navigationController pushViewController:user animated:YES];
    }
    if (indexPath.item == 2) {
//        MapViewController *map = [[MapViewController alloc]init];
//        map.str = @"蓝欧科技";
//        [self.navigationController pushViewController:map animated:YES];
        _geocoder = [[CLGeocoder alloc] init];
        [self listPlacemark];
    }
    if (indexPath.item == 3) {
        //发邮件
        [self sendMailInApp];
    }
    //关于我们页面
    if (indexPath.item == 4) {
        AboutUsVC *aboutUs = [[AboutUsVC alloc]init];
        [self.navigationController pushViewController:aboutUs animated:YES];
    }
    //清除缓存
    if (indexPath.item == 5) {
        //清除缓存
        NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
        CGFloat h = [ClearData folderSizeAtPath:path];
        NSString *str = [NSString stringWithFormat:@"是否清除%.2lfM内存?",h];
        UIAlertController *aler = [UIAlertController alertControllerWithTitle:nil message:str preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *quxiao = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
        UIAlertAction *queding = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
            [ClearData clearCache:path];
            [self.collectionView reloadData];
        }];
        [aler addAction:quxiao];
        [aler addAction:queding];
        [self presentViewController:aler animated:YES completion:^{
        }];
    }
    //一键换肤
    if (indexPath.item == 6) {
        
        
        SkinViewController *skin = [[SkinViewController alloc]init];
        skin.str = self.strstr;
        [self.navigationController pushViewController:skin animated:YES];
       
    }
    //在线客服
    if (indexPath.item == 7) {
        dispatch_async(dispatch_get_main_queue(), ^{
            self.hidesBottomBarWhenPushed = YES;
            RCConversationViewController *vc = [[RCConversationViewController alloc] initWithConversationType:(ConversationType_PRIVATE ) targetId:@"wang"];
            
            [self.navigationController pushViewController:vc animated:YES];
            self.hidesBottomBarWhenPushed = NO;
        });

    }
    //扫一扫
    if (indexPath.item == 8) {
        if ([QRCodeReader supportsMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]]) {
            static QRCodeReaderViewController *reader = nil;
            static dispatch_once_t onceToken;
            dispatch_once(&onceToken, ^{
                reader = [QRCodeReaderViewController new];
            });
            reader.delegate = self;
            [reader setCompletionWithBlock:^(NSString *resultAsString) {
                NSLog(@"Completion with result: %@", resultAsString);
            }];
            [self presentViewController:reader animated:YES completion:NULL];
        }else {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Reader not supported by the current device" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alert show];}
    }
}
#pragma mark - // 激活邮件功能
- (void)sendMailInApp{
    Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
    if (!mailClass) {
        UIAlertView *alert =[[UIAlertView alloc] initWithTitle:nil message:@"当前系统版本不支持应用内发送邮件功能，您可以使用mailto方法代替" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
        [alert show];
        [alert dismissWithClickedButtonIndex:0 animated:YES];
        return;
    }if (![mailClass canSendMail]) {
        UIAlertView *alert =[[UIAlertView alloc] initWithTitle:nil message:@"用户没有设置邮件账户" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
        [alert show];
        [alert dismissWithClickedButtonIndex:0 animated:YES];
        return;
    }
    [self displayMailPicker];
}

//调出邮件发送窗口
- (void)displayMailPicker{
    MFMailComposeViewController *mailPicker = [[MFMailComposeViewController alloc] init];
    mailPicker.mailComposeDelegate = self;
    [mailPicker setTitle:@"内容"];
    //设置主题
    [mailPicker setSubject: @"意见反馈"];
    //添加收件人
    NSArray *toRecipients = [NSArray arrayWithObject: @"939495554@qq.com"];
    [mailPicker setToRecipients: toRecipients];
    //添加抄送
    NSArray *ccRecipients = [NSArray arrayWithObjects:@"275400625@163.com", @"third@example.com", nil];
    [mailPicker setCcRecipients:ccRecipients];
    //添加密送
    NSArray *bccRecipients = [NSArray arrayWithObjects:@"fourth@example.com", nil];
    [mailPicker setBccRecipients:bccRecipients];
    
    NSString *emailBody = @"<font color='red'>eMail</font> 正文";
    [mailPicker setMessageBody:emailBody isHTML:YES];
    [self presentViewController:mailPicker animated:YES completion:^{
    }];
}
#pragma mark - 实现 MFMailComposeViewControllerDelegate
- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error{
    //关闭邮件发送窗口
    [self dismissViewControllerAnimated:YES completion:^{
    }];
    NSString *msg;
    switch (result) {
        case MFMailComposeResultCancelled:
            msg = @"用户取消编辑邮件";
            break;
        case MFMailComposeResultSaved:
            msg = @"用户成功保存邮件";
            break;
        case MFMailComposeResultSent:
            msg = @"用户点击发送，将邮件放到队列中，还没发送";
            break;
        case MFMailComposeResultFailed:
            msg = @"用户试图保存或者发送邮件失败";
            break;
        default:
            break;
    }
    NSLog(@"%@", msg);
}

#pragma mark - // QRCodeReaderDelegate方法实现
- (void)reader:(QRCodeReaderViewController *)reader didScanResult:(NSString *)result{
    //当前扫描到的网址
    self.webUrl = result;
    //跳转到网址
    [self dismissViewControllerAnimated:YES completion:^{
        self.alertview = [[UIAlertView alloc] initWithTitle:@"将要前往" message:result delegate:self cancelButtonTitle:@"前往" otherButtonTitles:nil];
        [self.alertview show];
    }];
}
#pragma mark - // 扫码弹出框的按钮协议方法
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if ([alertView isEqual:_alertview]) {
        //当前的下标如果是0 就是前往网页的按钮
        if (buttonIndex == 0) {
            ScanVC *scanVC = [ScanVC new];
            //将前往的网址传递
            scanVC.webString = self.webUrl;
            [self.navigationController pushViewController:scanVC animated:YES];
        }
    }
}
#pragma mark - // 取消扫描方法
- (void)readerDidCancel:(QRCodeReaderViewController *)reader{
    [self dismissViewControllerAnimated:YES completion:NULL];
}
-(void)location{
    //根据“”进行地理编码
    [_geocoder geocodeAddressString:@"大连软件园10号楼" completionHandler:^(NSArray *placemarks, NSError *error) {
        CLPlacemark *clPlacemark=[placemarks firstObject];//获取第一个地标
        MKPlacemark *mkplacemark=[[MKPlacemark alloc]initWithPlacemark:clPlacemark];//定位地标转化为地图的地标
        NSDictionary *options=@{MKLaunchOptionsMapTypeKey:@(MKMapTypeStandard)};
        MKMapItem *mapItem=[[MKMapItem alloc]initWithPlacemark:mkplacemark];
        [mapItem openInMapsWithLaunchOptions:options];
    }];
}
-(void)listPlacemark{
    //根据“北京市”进行地理编码
    [_geocoder geocodeAddressString:@"大连软件园10号楼"completionHandler:^(NSArray *placemarks, NSError *error) {
        CLPlacemark *clPlacemark1=[placemarks firstObject];//获取第一个地标
        MKPlacemark *mkPlacemark1=[[MKPlacemark alloc]initWithPlacemark:clPlacemark1];
        //注意地理编码一次只能定位到一个位置，不能同时定位，所在放到第一个位置定位完成回调函数中再次定位
        [_geocoder geocodeAddressString:@"大连软件园10号楼" completionHandler:^(NSArray *placemarks, NSError *error) {
            CLPlacemark *clPlacemark2=[placemarks firstObject];//获取第一个地标
            MKPlacemark *mkPlacemark2=[[MKPlacemark alloc]initWithPlacemark:clPlacemark2];
            NSDictionary *options=@{MKLaunchOptionsMapTypeKey:@(MKMapTypeStandard)};
            //MKMapItem *mapItem1=[MKMapItem mapItemForCurrentLocation];//当前位置
            MKMapItem *mapItem1=[[MKMapItem alloc]initWithPlacemark:mkPlacemark1];
            MKMapItem *mapItem2=[[MKMapItem alloc]initWithPlacemark:mkPlacemark2];
            [MKMapItem openMapsWithItems:@[mapItem1,mapItem2] launchOptions:options];
            
        }];
        
    }];
}
- (void)denglu{
    
    
    NSLog(@"登陆");
    
    
    _tencentOAuth = [[TencentOAuth alloc] initWithAppId:@"1105274920" andDelegate:self];
    
    if (_tencentOAuth.accessToken) {
        [_tencentOAuth setAccessToken:_tencentOAuth.accessToken];
        [_tencentOAuth setOpenId:_tencentOAuth.openId];
        [_tencentOAuth setExpirationDate:_tencentOAuth.expirationDate];
        
    }else{
        NSArray* permissions = [NSArray arrayWithObjects:
                                kOPEN_PERMISSION_GET_USER_INFO,
                                kOPEN_PERMISSION_GET_SIMPLE_USER_INFO,
                                kOPEN_PERMISSION_ADD_ALBUM,
                                kOPEN_PERMISSION_ADD_ONE_BLOG,
                                kOPEN_PERMISSION_ADD_SHARE,
                                kOPEN_PERMISSION_ADD_TOPIC,
                                kOPEN_PERMISSION_CHECK_PAGE_FANS,
                                kOPEN_PERMISSION_GET_INFO,
                                kOPEN_PERMISSION_GET_OTHER_INFO,
                                kOPEN_PERMISSION_LIST_ALBUM,
                                kOPEN_PERMISSION_UPLOAD_PIC,
                                kOPEN_PERMISSION_GET_VIP_INFO,
                                kOPEN_PERMISSION_GET_VIP_RICH_INFO,
                                nil];
        
        [_tencentOAuth authorize:permissions inSafari:NO];
    }
}
#pragma mark - 登陆的协议方法


#pragma mark - qq回调协议
- (void)getUserInfoResponse:(APIResponse*) response
{
    // 三方登陆获取的头像数据
    //    "figureurl_qq_1" = "http://q.qlogo.cn/qqapp/1105164233/877B7E00A3B8F2A5CEF1CE00E9883BAB/40";
    //    "figureurl_qq_2" = "http://q.qlogo.cn/qqapp/1105164233/877B7E00A3B8F2A5CEF1CE00E9883BAB/100";
    NSLog(@"%@",response.jsonResponse);//打印用户信息
    NSLog(@"%@",[response.jsonResponse objectForKey:@"nickname"]);//打印用户昵称
    
    NSString *nameString = [response.jsonResponse objectForKey:@"nickname"];
    NSString *imageString = [NSString stringWithFormat:@"%@",[response.jsonResponse objectForKey:@"figureurl_qq_2"]];//用户头像
    // 单例保存
    [[NSUserDefaults standardUserDefaults] setObject:nameString forKey:@"name"];
    [[NSUserDefaults  standardUserDefaults] setObject:imageString forKey:@"image"];
    NSLog(@"%@", [[NSUserDefaults standardUserDefaults] objectForKey:@"image"]);
  
    
}

#pragma mark - 点击取消键盘

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}
-(void)tencentDidLogin
{
    //    _labelTitle.text = @"登录完成";
    if (_tencentOAuth.accessToken && 0 != [_tencentOAuth.accessToken length])
    {
        //  记录登录用户的OpenID、Token以及过期时间
        //        _labelAccessToken.text = _tencentOAuth.accessToken;
        NSLog(@"%@", _tencentOAuth.accessToken);
        [_tencentOAuth accessToken];
        [_tencentOAuth openId];
        [_tencentOAuth expirationDate];
        
        [_tencentOAuth getUserInfo];
        NSLog(@"登陆成功");
    }
    else
    {
        //        _labelAccessToken.text = @"登录不成功 没有获取accesstoken";
        NSLog(@"登陆不成功, 没有获取accesstoken");
    }
}

-(void)tencentDidNotLogin:(BOOL)cancelled
{
    if (cancelled)
    {
        //        _labelTitle.text = @"用户取消登录";
        NSLog(@"用户取消登陆");
    }
    else
    {
        //        _labelTitle.text = @"登录失败";
        NSLog(@"登陆失败");
    }
}
- (void)tencentDidNotNetWork
{
    NSLog(@"网络问题登录失败");
}
- (NSArray *)getAuthorizedPermissions:(NSArray *)permissions
                      withExtraParams:(NSDictionary *)extraParams
{
    NSLog(@"~~~~~~~%@\n %@", permissions, extraParams);
    return permissions;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
